import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author gao
 * @date 2025/8/11 10:21
 */

public class Demo7 {
    private static void readFile1() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("./test.txt");
            while (true) {
                byte[] bytes = new byte[1024];
                int n = inputStream.read(bytes);
                if (n == -1) {
                    break;
                }
                for (int i = 0; i < n; i++) {
                    System.out.printf("%x", bytes[i]);
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream == null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void readFile2() {
        // try with resource 简化语法
        // try语句执行结束之后，会自动调用close方法
        try (InputStream inputStream = new FileInputStream("./test.txt")) {
            while (true) {
                byte[] bytes = new byte[1024];
                int n = inputStream.read(bytes);
                if (n == -1) {
                    break;
                }
                for (int i = 0; i < n; i++)
                    System.out.printf("%x", bytes[i]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        readFile2();
    }
}